package com.javatiaocao.myblog.service.impl;

import com.javatiaocao.myblog.constant.CodeType;
import com.javatiaocao.myblog.mapper.*;
import com.javatiaocao.myblog.model.Article;
import com.javatiaocao.myblog.model.User;
import com.javatiaocao.myblog.model.Visitor;
import com.javatiaocao.myblog.service.StatisticsInfoService;
import com.javatiaocao.myblog.utils.DataMap;
import com.javatiaocao.myblog.utils.StringUtil;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

@Service
public class StatisticsInfoServiceImpl implements StatisticsInfoService {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private VisitorMapper visitorMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private RedisServiceImpl redisServiceImpl;

    @Autowired
    private StatisticMapper statisticMapper;

    @Autowired
    private TagMapper tagMapper;

    @Autowired
    private LeaveWordMapper leaveWordMapper;

    @Autowired
    private CommentMapper commentMapper;
    
    @Autowired
    private HashRedisServiceImpl hashRedisServiceImpl;

    private static final String TOTAL_VISITOR = "totalVisitor";
    private static final String PAGE_VISITOR = "pageVisitor";


    /**
     * 仪表盘信息
     *
     * @param request
     * @param userDetails
     * @return
     */
    @Override
    public DataMap getStatisticsInfo(HttpServletRequest request, UserDetails userDetails) {
        HashMap<String, Object> dataMap = new HashMap<>();
        //获取总访问量
        long allVisitor = redisServiceImpl.getVisitorNumOnRedis(StringUtil.VISITOR,"totalVisitor");
        //昨日访问量
        long yesterdayVisitor = redisServiceImpl.getVisitorNumOnRedis(StringUtil.VISITOR,"yesterdayVisitor");
        dataMap.put("allVisitor",allVisitor);
        dataMap.put("yesterdayVisitor",yesterdayVisitor);
//        Object allVisitor = redisTemplate.opsForHash().get("visitor","totalVisitor");
//        if (allVisitor == null){
//            return DataMap.fail(CodeType.SERVER_EXCEPTION);
//        }
//        Visitor yesterdayVisitor = visitorMapper.getVisitorNum("visitorVolume");
//
//        if (yesterdayVisitor == null){
//            return DataMap.fail(CodeType.SERVER_EXCEPTION);
//        }
//
        //总用户
        int allUser = userMapper.getallUser();
        if (allUser == 0){
            return DataMap.fail(CodeType.SERVER_EXCEPTION);
        }
        dataMap.put("allUser",allUser);

        //总文章
        int articleNum = articleMapper.countArticle();
        if (articleNum == 0){
            return DataMap.fail(CodeType.SERVER_EXCEPTION);
        }
        dataMap.put("articleNum",articleNum);

        //点赞量TODO
        List<Article> articleList = articleMapper.selectArticleByNameWithPage(userDetails.getUsername());
        int isReadNum = 0;
        for (Article article : articleList) {
            isReadNum += statisticMapper.isReadLikeMessage(article.getArticleId());
        }
        dataMap.put("articleThumbsUpNum",isReadNum);

//
//
//        JSONObject data = new JSONObject();
//        data.put("allVisitor",allVisitor);
//        data.put("yesterdayVisitor",yesterdayVisitor.getVisitorNum());
//        data.put("allUser",allUser);
//        data.put("articleNum",articleNum);
//        data.put("articleThumbsUpNum",0);
//
//        return DataMap.success().setData(data);
        return  DataMap.success().setData(dataMap);
    }

    /**
     * 获取浏览量
     * @param pageName
     * @param request
     * @return
     */
    @Override
    public DataMap getVisitorNumByPageName(String pageName, HttpServletRequest request) {
        HashMap<String, Object> dataMap = new HashMap<>();
        //获取访问页面visitor
        String visitor =(String) request.getSession().getAttribute(pageName);

        //判断是否访问过
        if(visitor == null){
            request.getSession().setAttribute(pageName,"yes");
            //增加当前页访问人数
            long pageVisitor = updatePageVisitor(visitor,pageName);

            //总访问人数
            long totalVisitor = redisServiceImpl.addVisitorNumToRedis(StringUtil.VISITOR,TOTAL_VISITOR,1);
            if(totalVisitor == 0){
                totalVisitor = visitorMapper.getTotalVisitorNum();
                totalVisitor = redisServiceImpl.putVisitorNumToRedis(StringUtil.VISITOR,TOTAL_VISITOR,1);
            }
            dataMap.put(TOTAL_VISITOR,totalVisitor);
            dataMap.put(PAGE_VISITOR,pageVisitor);

            return DataMap.success().setData(dataMap);
        }
        long pageVisitor = redisServiceImpl.getVisitorNumOnRedis(StringUtil.VISITOR,pageName);
        long totalVisitor =redisServiceImpl.getVisitorNumOnRedis(StringUtil.VISITOR,TOTAL_VISITOR);
        dataMap.put(TOTAL_VISITOR,totalVisitor);
        dataMap.put(PAGE_VISITOR,pageVisitor);

        return DataMap.success().setData(dataMap);

    }

    /**
     * 网站信息获取
     * @return
     */
    @Override
    public DataMap getSiteInfo() {
        HashMap<String, Object> dataMap = new HashMap<>();
        int articleNum = articleMapper.countArticle();
        int tagsNum = tagMapper.countTagNum();
        int leaveWordNum = leaveWordMapper.countLeaveWordNum();
        int commentNum = commentMapper.countCommentNum();

        dataMap.put("articleNum",articleNum);
        dataMap.put("tagsNum",tagsNum);
        dataMap.put("leaveWordNum",leaveWordNum);
        dataMap.put("commentNum",commentNum);

        return DataMap.success().setData(dataMap);
    }

    @Override
    public DataMap getUserNews(String username) {
        HashMap<String, Object> objectHashMap = new HashMap<>();
        int userId = userMapper.findUserByPhone(username).getId();
        //根据id查询用户信息
        LinkedHashMap allFieldAndValueMap =(LinkedHashMap) hashRedisServiceImpl.getAllFieldAndValue(String.valueOf(userId));

        JSONObject jsonObject = new JSONObject();
        if (allFieldAndValueMap.size() == 0){
            objectHashMap.put("result",0);
        }else {
            int allNewsNum = (int)allFieldAndValueMap.get("allNewsNum");
            int commentNum = (int)allFieldAndValueMap.get("commentNum");
            int leaveMessageNum = (int)allFieldAndValueMap.get("leaveMessageNum");
            jsonObject.put("allNewsNum",allNewsNum);
            jsonObject.put("commentNum",commentNum);
            jsonObject.put("leaveMessageNum",leaveMessageNum);
            objectHashMap.put("result",jsonObject);
        }

        return DataMap.success().setData(objectHashMap);

    }


    /**
     *
     * 更新页面访问量
     *
     * */
    private long updatePageVisitor(String visitor, String pageName) {
        Visitor thisVisitor ;
        Long pageVisitor = 0L;
        if (visitor == null){
           pageVisitor = redisServiceImpl.addVisitorNumToRedis(StringUtil.VISITOR,pageName,1);
        }
        if (pageVisitor == 0){
            thisVisitor = visitorMapper.getVisitorNum(pageName);
            if (thisVisitor != null){
                redisServiceImpl.putVisitorNumToRedis(StringUtil.VISITOR,pageName,pageVisitor + 1);
            }else {
                return  0L;
            }
        }

        return pageVisitor;
    }
}
